(function () {
    var core = ecui,
        dom = core.dom,
        ui = core.ui,
        util = core.util,
        now = new Date(),
        venues = [];

    NS.ui.VenueSelectEdit = ecui.inherits(
        mao.ui.SelectEdit,
        {
            onchange: function (event) {
                mao.ui.SelectEdit.prototype.onchange.call(this, event);

                var venueId = this.getValue(),
                    yard = dom.children(dom.next(dom.getParent(this.getMain())))[1],
                    yards = venues.find(function (item) { return item.id === venueId; });

                yards = yards ? yards.children : [];
                ecui.dispose(yard);
                yard.innerHTML = yards.map(function (item) {
                    return ecui.esr.getEngine().render('yardItem', { item: item });
                }).join('');
                ecui.init(yard);
            }
        }
    );
    NS.ui.StateSwitch = ecui.inherits(
        ecui.ui.BSwitch,
        function (el, options) {
            ecui.ui.BSwitch.call(this, el, options);
            this._sOptId = options.optId;
        },
        {
            getFormValue: function () {
                return this.isChecked() ? 2 : 1;
            },
            isFormChecked: function () {
                return true;
            }
        }
    );
    NS.ui.HasProjectRadio = ecui.inherits(
        ecui.ui.Radio,
        {
            inputs: [],
            $click: function (event) {
                ecui.ui.Radio.prototype.$click.call(this, event);
                this.clickHandler();
            },
            clickHandler: function () {
                var projectId = ecui.get('project-id');
                if (projectId) {
                    projectId.getParent()[this.getValue() === '2' ? 'hide' : 'show']();
                    projectId.getParent()[this.getValue() === '2' ? 'disable' : 'enable']();
                }
                this.toggleInput(this.getValue() === '2');
            },
            toggleInput: function (isShow) {
                this.inputs.forEach(function (item) {
                    item[isShow ? 'enable' : 'disable']();
                }.bind(this));
            },
            init: function () {
                ecui.ui.Radio.prototype.init.call(this);
                util.timer(function () {
                    if (this.isChecked()) {
                        this.clickHandler();
                    }
                }, 0, this);
            }
        }
    );

    function saveOrderFn (me, isEdit, isConfirm) {
        if (me.isSending) {
            return;
        }
        var form = document.forms.editProjectRoundForm,
            data = {},
            vaild = ecui.esr.parseObject(form, data),
            startTime = new Date(data.projectRound.startTime.replace(/-/g, '/')),
            endTime = new Date(data.projectRound.endTime.replace(/-/g, '/'));
        if (startTime > endTime) {
            return ecui.tip('wrrong', '开始时间不能大于结束时间');
        }

        if (!vaild) {
            ecui.tip('warn', '请完成所有必填项的输入');
            return;
        }
        var url = '/erp-management/project/and-round/add',
            paramData = {
                project: data.project,
                projectRound: data.projectRound
            };
        if (data.hasProject === '1') {
            url = '/erp-management/project/add-round';
            paramData = {
                projectId: data.projectId
            };
            Object.assign(paramData, data.projectRound);
            paramData.musicianId = paramData.musicianIds;
            delete paramData.musicianIds;
        } else {
            paramData.projectRound.musicianId = paramData.projectRound.musicianIds;
            delete paramData.projectRound.musicianIds;
        }
        if (isEdit) {
            url = '/erp-management/project/and-round/update';
        }
        ecui.esr.setData('addProjectRoundData', paramData);
        me.isSending = true;
        ecui.esr.request(
            util.stringFormat('data@JSON {0}?${addProjectRoundData}{1}', url, isConfirm ? '&confirmAdd=true' : ''),
            function () {
                me.isSending = false;
                var data = ecui.esr.getData('data');
                if (data instanceof Object) {
                    if (isEdit) {
                        ecui.tip('warn', '编辑预定场订单成功');
                        if (ecui.esr.getData('type') === 'venueOrder') {
                            delete ecui.esr.getRoute('/venueOrder/detail').CACHE;
                            history.go(-1);
                        } else {
                            delete ecui.esr.getRoute('/approval/initiate.initiate').CACHE;
                            ecui.esr.redirect('/approval/initiate.initiate');
                        }
                    } else {
                        ecui.tip('warn', '新增预定场订单成功');
                        var route = ecui.esr.getRoute('/venueOrder/calendar');
                        delete route.CACHE;
                        route.day = startTime;
                        history.go(-1);
                    }
                } else if (data === 20001) {
                    ecui.confirm(
                        '<p class="confirm-title">提示</p><p>该时间段已有其他场次是否继续？</p>',
                        function () {
                            saveOrderFn(me, isEdit, true);
                        }
                    );
                } else if (data === 20002) {
                    ecui.confirm(
                        '<p class="confirm-title">提示</p><p>该意向名称已被使用是否继续？</p>',
                        function () {
                            saveOrderFn(me, isEdit, true);
                        }
                    );
                }
            },
            function () {
                me.isSending = false;
                ecui.tip('warn', '请完成所有必填项的输入');
            }
        );
    }

    NS.ui.SubmitProjectRound = ecui.inherits(
        mao.ui.Submit,
        function (el, options) {
            mao.ui.Submit.call(this, el, options);
            this._sOptId = options.optId;
        },
        {
            $click: function () {
                saveOrderFn(this, !!this._sOptId, true);
            }
        }
    );

    ecui.esr.addRoute('edit', {
        model: function (context, callback) {
            var model = [
                'detail@GET /erp-management/project/modify-round/${id}',
                'venues@GET /erp-management/venue/select-list-all'
            ];
            if (!context.id) {
                model.splice(0, 1);
            }
            ecui.esr.request(model, callback);
            return false;
        },
        weight: 10,
        frame: true,
        notleave: true,
        onbeforerender: function (context) {
            ecui.esr.setData('orderEditTitle', context.id ? '编辑订场' : '新增订场');
            mao.util.setTitle(context.id ? '编辑订场' : '新增订场');
            context.start = ecui.util.formatDate(context.detail ? new Date(context.detail.startTime) : now, 'yyyy-MM-dd 16:00:00');
            context.end = ecui.util.formatDate(context.detail ? new Date(context.detail.startTime) : now, 'yyyy-MM-dd 23:59:00');

            if (!context.id && context.day) {
                context.start = context.day + ' 16:00:00';
                context.end = context.day + ' 22:59:00';
            }

            var yards = [];
            var venueId = context.detail ? context.detail.venueId : mao.staffInfo.venueList[0];
            for (var i = 0, item; item = context.venues[i++]; ) {
                if (venueId === item.id) {
                    yards = item.children;
                    break;
                }
            }
            context.yards = yards;
            venues = context.venues;
            if (context.detail) {
                context.projectTypeDesc = context.detail.project.projectTypeList.map(function (item) { return item.projectName; }).join('，');
                context.projectTypeIds = context.detail.project.projectTypeList.map(function (item) { return item.projectType; }).join(',');
            }
        },
        onafterrender: function (context) {
        },
        oncached: function () {
            this.notleave = true;
        },
        onleave: function (context, callback) {
            if (this.notleave && ecui.util.checkUpdate(document.forms.editProjectRoundForm)) {
                ecui.$messagebox(
                    'ui-messagebox-confirm',
                    '是否放弃正在编辑的信息？',
                    ['继续编辑', '放弃编辑'],
                    function () {
                        callback(false);
                    },
                    function () {
                        callback(true);
                    }
                );
                return false;
            }
        }
    });
}());